<template>
  <!-- 添加分类的对话框 -->
  <el-dialog
    title="修改分类"
    v-model="editDialogVisible"
    width="50%"
    @close="editDialogClose"
  >
    <!-- 内容主体区域 -->
    <!-- 表单中model和rules名称不可以相同 -->
    <el-form
      ref="editCateFormRef"
      :model="editCateForm"
      :rules="editCateFormRules"
      label-width="80px"
    >
      <el-form-item label="分类名称" prop="cateName">
        <el-input v-model="editCateForm.cateName"></el-input>
      </el-form-item>
      <el-form-item label="父级分类">
        <el-cascader
          style="width:100%"
          v-model="selectedKeys"
          :options="cateKeyNames"
          :props="{
            checkStrictly: true,
            expandTrigger: 'hover',
            value: 'id',
            label: 'cateName',
            children: 'children'
          }"
          @change="parentCateChange"
          clearable
        >
        </el-cascader>
      </el-form-item>
    </el-form>
    <!-- 底部区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogClose">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { editCategory } from "network/category.js";
export default {
  props: {
    editDialogVisible: {
      type: Boolean,
      default: false
    },
    // 级联选择器绑定的数据源
    cateKeyNames: {
      type: Array,
      default: []
    },
    // 表单的验证规则对象
    editCateFormRules: {
      type: Object,
      default: {}
    },
    editCateForm: {
      type: Object,
      default: {}
    },
    // 级联选择器选定的数据
    selectedKeys: {
      type: Array,
      defalt: []
    }
  },
  data() {
    return {};
  },
  emits: ["editDialogClose"],
  methods: {
    //监听添加用户对话框的关闭事件
    editDialogClose() {
      this.$emit("editDialogClose");
    },
    //选择项发生变化,触发函数
    parentCateChange() {
      if (this.selectedKeys && this.selectedKeys.length > 0) {
        this.editCateForm.level = this.selectedKeys.length;
        this.editCateForm.parentId = this.selectedKeys[
          this.selectedKeys.length - 1
        ];
      } else {
        this.editCateForm.level = 0;
        this.editCateForm.parentId = "";
      }
    },
    async editCate() {
      this.$refs.editCateFormRef.validate(async valid => {
        // console.log(valid);//校验成功true,失败false
        if (!valid) return;
        //发起网络请求
        console.log(this.editCateForm);
        const res = await editCategory(this.editCateForm);
        if (res.status !== 200)
          return this.$message.error({ showClose: true, message: res.msg });
        this.$message.success({ showClose: true, message: res.msg });
        this.$emit("editDialogClose", true);
      });
    }
  }
};
</script>

<style lang="less" scoped></style>
